<template>
  <e-container :loading="loading">
    <e-title title="Create Price Change Application" />
    <a-divider />
    <div class="form">
      <a-form ref="formInstance" :model="apiDataBase" layout="vertical" :rules="rules">
        <a-row :gutter="gutter">
          <a-col :span="24">
            <a-form-item label="Subject" name="theme">
              <a-input v-model:value="apiDataBase.theme" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="gutter">
          <a-col :span="24">
            <a-form-item label="Language Pair" name="langPairID">
              <a-select
                v-model:value="apiDataBase.langPairID"
                mode="multiple"
                :get-popup-container="triggerNode => triggerNode.parentNode"
                option-filter-prop="label">
                <a-select-option v-for="item in languagePairs" :key="item.langPairID" :label="item.langPairName">
                  {{ item.langPairName }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="gutter">
          <a-col :span="12">
            <a-form-item label="BUM" name="bumid">
              <a-select v-model:value="apiDataBase.bumid" :get-popup-container="triggerNode => triggerNode.parentNode">
                <a-select-option v-for="item in bumCandidates" :key="item.empID">
                  {{ item.empName }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="Attachment (Price Sheet)" name="fileName">
              <a-input :value="fileName" :readonly="true">
                <template #addonAfter>
                  <input v-show="false" ref="uploadInput" type="file" @change="uploadFileChange" />
                  <span style="color: #a9b5c9; cursor: pointer" @click="uploadInput.click()">
                    <e-icon type="upload" style="margin-right: 6px" />Upload
                  </span>
                </template>
              </a-input>
            </a-form-item>
          </a-col>
        </a-row>
        <a-divider />
        <a-row :gutter="gutter">
          <a-col :span="12">
            <a-form-item label="Phase Progress">
              <a-input disabled :value="'Phase ' + (briefInfo.phaseID === -1 ? 0 : briefInfo.phaseID)" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="gutter">
          <a-col :span="12">
            <a-form-item label="Client Name">
              <a-input disabled :value="briefInfo.fullName" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="Country/Region">
              <a-input disabled :value="transformedBasicInfo.countryID" />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="gutter">
          <a-col :span="12">
            <a-form-item label="Business Area">
              <a-input disabled :value="transformedBasicInfo.businessDirection" />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="Currency">
              <a-input disabled :value="transformedBasicInfo.currencyID" />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <a-divider />
    <div class="buttons">
      <a-space size="middle">
        <a-button @click="handleCancel">Cancel</a-button>
        <a-button type="primary" :disabled="!saveButtonAvailable" @click="handleSave()">Create</a-button>
      </a-space>
    </div>
  </e-container>
</template>

<script setup>
import { computed, inject, reactive, ref } from 'vue'
import { useStore } from 'vuex'
import EContainer from '@/components/EContainer.vue'
import ServicePrice from '@/api/client/servicePrice.js'
import { APPLY_CREATED, CONFIRM_BACK_TO_DETAIL, UPLOAD_FAILED } from '@/constants/message.js'
import { useRoute, useRouter } from 'vue-router'
import { useBasicInfo } from '@/pages/Client/hooks/useBasicInfo.js'
import TargetClient from '@/api/targetClient.js'
const store = useStore()
const route = useRoute()
const router = useRouter()
const { Modal, message } = inject('Feedback')
const loading = ref(true)
const saveButtonAvailable = ref(true)
const gutter = [120, 16]
const briefInfo = computed(() => store.state.client.briefInfo)
const { id } = route.params
const apiDataBase = reactive({
  theme: '',
  langPairID: [],
  bumid: undefined
})
const apiDataAttach = reactive({
  attachmentAddr: '',
  attachmentFileSize: 0,
  attachmentName: ''
})
const uploadInput = ref(null)
const fileName = ref('')
const uploadFileChange = event => {
  if (event.target.files.length > 0) {
    TargetClient.uploadFiles(event.target.files)
      .then(res => {
        if (Array.isArray(res) && res.length > 0 && res[0] instanceof Eci.IO.File) {
          fileName.value = event.target.files.length > 0 ? event.target.files[0].name : ''
          apiDataAttach.attachmentAddr = res[0].Path
          apiDataAttach.attachmentFileSize = res[0].SourceBaseFileSize
          apiDataAttach.attachmentName = fileName.value
          formInstance.value.clearValidate('fileName')
        } else {
          fileName.value = ''
          uploadInput.value.value = null
          message.error(UPLOAD_FAILED)
        }
      })
      .catch(() => {
        fileName.value = ''
        message.error(UPLOAD_FAILED)
      })
  }
}
const languagePairs = ref([])
const bumCandidates = ref([])
ServicePrice.getBumCandidates(id).then(({ data }) => {
  bumCandidates.value = data
  if (Array.isArray(bumCandidates.value) && bumCandidates.value.length > 0) {
    apiDataBase.bumid = bumCandidates.value[0].empID
  }
})
const transformedBasicInfo = ref({})
const formInstance = ref(null)
const emits = defineEmits(['updated'])
new Promise(resolve => {
  useBasicInfo(id, resolve, true)
})
  .then(({ raw, transformed }) => {
    transformedBasicInfo.value = transformed.value
    ServicePrice.getLanguagePair(raw.value.id, raw.value.fromGrade).then(({ data }) => {
      languagePairs.value = data
    })
  })
  .finally(() => {
    loading.value = false
  })
const rules = {
  theme: [
    {
      required: true,
      whitespace: true,
      message: 'Please Input Subject',
      trigger: 'blur'
    }
  ],
  langPairID: [
    {
      type: 'array',
      required: true,
      message: 'Please select at least a pair of language',
      trigger: 'blur'
    }
  ],
  bumid: [
    {
      type: 'number',
      required: true,
      message: 'Please Select BUM',
      trigger: 'blur'
    }
  ]
}
const handleSave = () => {
  formInstance.value.validate().then(() => {
    saveButtonAvailable.value = false
    ServicePrice.createQuoteApply(id, apiDataBase, apiDataAttach)
      .then(({ data }) => {
        message.success(APPLY_CREATED)
        setTimeout(() => {
          window.open(router.resolve({ name: 'Price', params: { id: data } }).href)
        }, 1000)
        router.replace({ name: 'Service Price', params: { id: id } })
        emits('updated')
      })
      .catch(() => {
        saveButtonAvailable.value = true
      })
  })
}
const handleCancel = () => {
  Modal.confirm({
    content: CONFIRM_BACK_TO_DETAIL,
    okButtonProps: { danger: true },
    onOk: () => {
      router.push({ name: 'Service Price', params: { id: id } })
    }
  })
}
</script>

<style lang="less" scoped>
.form {
  padding: 0 228px;
}
.buttons {
  text-align: center;
}
</style>
<route lang="yaml">
name: CreateOrEditChangeApplication
path: /client/:id/service-price/create
meta:
  title: Create Price Change Application
  permission: ServicePrice
</route>
